//
//  DeliveryInfoViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-5-20.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "DeliveryInfoViewController.h"
#import "DeliveryInfoCellViewController.h"
#import "ModifyDeliveryInfoViewController.h"
#import "M13UserDefaults.h"
#import "GDataXMLNode.h"
#import "ELifeAppDelegate.h"
#import "GTMBase64.h"
#import "AlertView.h"
#import "GetMyData.h"
#import "ModifyDeliveryInfoViewController.h"
#import "DeliveryInfoModelList.h"
#import "DeliveryInfoModel.h"
#import "LoginController.h"


@implementation DeliveryInfoViewController

@synthesize tableView;

int tableViewSelectedRow;
static UITableViewCell *checkedCell;

DeliveryInfoModelList* list;

- (void)del
{
    NSString* userid = [GetMyData getUserId];
    if (userid == nil)
    {
        
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
        
    }
    //6.2 删除邮寄地址
    //请求地址: /mailing_address.php
    //请求参数: action  => deletemailingaddress
    //mail_id => 邮寄地址ID
    //user_id => 用户id
    //返回参数: 
    //返回格式事例: <?xml version="1.0" encoding="UTF-8"?><msg><head><returncode>0</returncode><transcode>deletemailingaddress</transcode></head></msg>
    //
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"mailing_address.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];

    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [param setObject:[GetMyData getUserId] forKey:@"user_id"];
    [param setObject:@"deletemailingaddress" forKey:@"action"];
    
    DeliveryInfoModel* model = [list.info objectAtIndex:tableViewSelectedRow];
    [param setObject:model.mail_id forKey:@"mail_id"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestDelFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[[ELifeAppDelegate App] httpRequestPoint]openUrl:dic postParam:param target:self];    [[ELifeAppDelegate App] showProgressDialog:@"请稍候"];
}

- (void)iRequestDelFinished:(NSData *)response
{
    //    返回格式事例: <?xml version="1.0" encoding="UTF-8"?><msg><head><returncode>0</returncode><transcode>addmailingaddress</transcode></head><body><mail_id>76</mail_id></body></msg>
    
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"rootElement:------%@\n", rootElement);
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    
    NSString* transcode = [[[headsElement elementsForName:@"transcode"] objectAtIndex:0] stringValue];
    
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    
    [doc release];
    
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
        [alert setTag:1];
        [alert release];
        return;
    } else if (code != 0){
        [AlertView showAlert:@"删除失败"];
        [doc release];
        return;
    } 
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"删除成功" delegate:self
											  cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert setTag:2];
    [alert show];
    [alert release];
}

- (void)search
{
    NSString* userid = [GetMyData getUserId];
    if (userid == nil)
    {
        LoginController* lc = [[LoginController alloc] init:self];
        lc.view.tag = 2001;
        //        [self.view addSubview:lc.view];
        [self.navigationController pushViewController:lc animated:NO];
        [lc release];
        
    }
    
    //6.3 获取邮寄地址列表
    //请求地址: /mailing_address.php
    //请求参数: action  => getmailingaddresslist
    //user_id => 用户ID
    //返回参数: mail_id 邮寄地址ID
    //user_id 用户ID
    //mail_people 联系人
    //mail_province 省份（暂未使用）
    //mail_address 邮寄地址
    //mail_zipcode 邮编
    //mail_email EMAIL（暂未使用）
    //mail_phone 联系电话
    //mail_accept 最佳配送时间（暂未使用）
    //time 邮寄地址创建时间（时间戳）
    //status 状态（1:显示；0:不显示）
    //from 来源
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"mailing_address.php"]];
    
    
    NSString* userName = [GetMyData getUserId];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    [param setObject:@"getmailingaddresslist" forKey:@"action"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [param setObject:userName forKey:@"user_id"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[[ELifeAppDelegate App] httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [[ELifeAppDelegate App] showProgressDialog:@"请稍候"];
    
    
//    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
//    [param setObject:@"getmailingaddresslist" forKey:@"action"];
//    NSString* userid = [GetMyData getUserId];
//    [param setObject:userid forKey:@"user_id"];
//    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
//    
//    NSString* urlRegister = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil], @"mailing_address.php?"];
//    
//    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlRegister], @"iRequestMailAddress:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
//    
//    
//    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
//    [param release];
}

- (void)iRequestFinished:(NSData *)response
{
    //返回格式事例： <?xml version="1.0" encoding="UTF-8"?><msg><head><returncode>0</returncode><transcode>getmailingaddresslist</transcode></head><body><mail_list><item><mail_id>1</mail_id><user_id>1</user_id><mail_people>冬天冷</mail_people><mail_address>北京市朝阳区花家地西里</mail_address><mail_zipcode>100020</mail_zipcode><mail_email></mail_email><mail_phone>1380013800</mail_phone><mail_accept></mail_accept><time>1294294763</time><default_time></default_time><status>1</status><from>659</from></item><item><mail_id>2</mail_id><user_id>1</user_id><mail_people>夏天热</mail_people><mail_address>北京市朝阳区花家地西里</mail_address><mail_zipcode>100020</mail_zipcode><mail_email></mail_email><mail_phone>13800138123</mail_phone><mail_accept></mail_accept><time>1291799676</time><default_time></default_time><status>1</status><from>659</from></item></mail_list></body></msg>1</status><from>659</from></item></mail_list>
    
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"rootElement:------%@\n", rootElement);
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
        [alert release];
        return;
    } 
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    NSLog(@"-----bodyElement-----%@\n", bodyElement);
    
    list = [DeliveryInfoModelList getInstance];
    
    //某个具体节点的文本内容
    GDataXMLElement* mail_list = [[bodyElement elementsForName:@"mail_list"]objectAtIndex:0];
    
    NSArray *items = [mail_list elementsForName:@"item"];    
    list.info = [[NSMutableArray alloc] initWithCapacity:[items count]];
    
    for (int i = 0; i < [items count]; i ++){
        GDataXMLElement *element = [items objectAtIndex:i];
        
        
        NSArray *arr = [element children];
        
        NSString* mail_address;
        NSString* mail_phone;
        NSString* mail_people;
        NSString* mail_zipcode;
        NSString* mail_id;        
        for (int j = 0; j<[arr count]; j++) {
            GDataXMLNode *node = [arr objectAtIndex:j];
            
            NSString* key = [node name];
            
            if ([key isEqualToString:@"mail_address"]){
                mail_address = [node stringValue];
            } else if  ([key isEqualToString:@"mail_phone"]){
                mail_phone = [node stringValue];
            } else if  ([key isEqualToString:@"mail_people"]){
                mail_people = [node stringValue];                               
            } else if  ([key isEqualToString:@"mail_zipcode"]){
                mail_zipcode = [node stringValue];                 
            } else if  ([key isEqualToString:@"mail_id"]){
                mail_id = [node stringValue];                 
            } 
        }
        
        DeliveryInfoModel* model = [[[DeliveryInfoModel alloc] init] autorelease];
        model.mail_address = mail_address;
        model.mail_people = mail_people;
        model.mail_phone = mail_phone;
        model.mail_zipcode = mail_zipcode;
        model.mail_id = mail_id;
        
        [list.info addObject:model];
    }

    [doc release];
    
    [self.tableView reloadData];
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    
    if (checkedCell != nil)
    {
        [checkedCell release];
    }
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    
    
    [self.navigationItem setTitle:@"配送资料"]; 
}

- (void)viewWillAppear:(BOOL)animated
{
    [self search];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [list.info count];
}

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *kCellIdentifier = @"DeliveryInfoCellID";
	
    DeliveryInfoCellViewController *cell;	
	cell = (DeliveryInfoCellViewController *)[table dequeueReusableCellWithIdentifier:kCellIdentifier];
    
	if (cell == nil)
	{
        NSArray *nib = [[NSBundle mainBundle]
                        loadNibNamed:@"DeliveryInfoCellView" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        if (tableViewSelectedRow == indexPath.row)
        {
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
            checkedCell = cell;
        } else {
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }
        
    }
    
    DeliveryInfoModel* model = [list.info objectAtIndex:indexPath.row];
    
//zipcode, name, address, phoneNumber
    [cell.zipcode setText:model.mail_zipcode];
    [cell.name setText:model.mail_people];
    [cell.address setText:model.mail_address];
    [cell.phoneNumber setText:model.mail_phone];
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [checkedCell setAccessoryType:UITableViewCellAccessoryNone];
    
    checkedCell = [self.tableView cellForRowAtIndexPath:indexPath];
    [checkedCell setAccessoryType:UITableViewCellAccessoryCheckmark];
    
    tableViewSelectedRow = indexPath.row;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120.0f;
}

-(void) change:(id)sender
{
    if (list == nil || [list.info count] == 0)
    {
        return;
    }
    ModifyDeliveryInfoViewController *controller;
    controller = [[ModifyDeliveryInfoViewController alloc] initWithNibName:@"ModifyDeliverView" bundle:nil];
    [controller setModel: [list.info objectAtIndex:tableViewSelectedRow]];
    [self.navigationController pushViewController:controller animated:YES];
}

-(void) deleteAInfo:(id)sender
{
    if (list == nil || [list.info count] == 0)
    {
        return;
    }
    [self del];
}

-(void) add:(id)sender
{
    ModifyDeliveryInfoViewController *controller;
    controller = [[ModifyDeliveryInfoViewController alloc] initWithNibName:@"ModifyDeliverView" bundle:nil];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark  -- UIAlertViewDelegate --  
//根据被点击按钮的索引处理点击事件  
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  
    NSLog(@"clickedButtonAtIndex:%d---%d",buttonIndex, alertView.tag);  
    if (buttonIndex == 0 && alertView.tag == 2)
    {
        [self search];
    }
}  

@end
